<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 被观察者
    class Subject {
      constructor() {
        this.observerList = []
      }

      // 添加观察者
      addObserver(ob) {
        this.observerList.push(ob)
      }

      //删除观察者
      deleteObserver(ob) {
        const index = this.observerList.findIndex(o => {
          return o.name === ob.name
        })
        this.observerList.splice(index, 1)
      }
      //通知观察者
      notifyObserver(message) {
        this.observerList.forEach(observer => {
          observer.notified(message)
        })
      }
    }

    class Observer {
      // 第二个参数，观察者创建之初，显示声明要被加入到的被观察者的通知列表内
      constructor(name, subject) {
        this.name = name;
        if (subject) {
          subject.addObserver(this)
        }
      }
      notified(message) {
        console.log(this.name, 'got message: ' + message)
      }
    }


    const subject = new Subject()
    const ob1 = new Observer('ob1', subject);
    const ob2 = new Observer('ob2');
    subject.addObserver(ob2);

    subject.notifyObserver('通知了')
    subject.deleteObserver(ob1)
    subject.notifyObserver('第二次通知')
  </script>
</body>

</html>